<?php
namespace app\model;
use think\Model;
use think\model\concern\SoftDelete;
class ChannelRecharge extends Model{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    //列表
    public function get_list($data){
        if(isset($data['channel_id']) && !empty($data['channel_id'])){
            $wh[] = ['cr.channel_id','=',$data['channel_id']];
        }
        if(isset($data['time']) && !empty($data['time'])){ 
            $t = explode('&',$data['time']); 
            $wh[] = ['cr.create_time','between',[strtotime($t[0]),strtotime($t[1])+86399]];
        }
        $wh[] = ['cr.id','>','0'];

        $arr['list'] = $this->alias('cr')
        ->field("cr.*,ch.name channel_name,acc.name_id,u.username")
        ->join('channel ch','cr.channel_id = ch.id',"LEFT")
        ->join('op_account acc','cr.op_account_id = acc.id',"LEFT")
        ->join('user u','cr.finance_id = u.id',"LEFT")
        ->where($wh)->order('cr.id desc')->page($data['page'],$data['limit'])->select();
        $arr['cnt'] = $this->alias('cr')->where($wh)->count('cr.id');
        return $arr;
    }

    //添加
    public function add($data){
        $validate = \think\facade\Validate::rule([
            'channel_id|端口名称'  => 'require',
            'rebate|端口返点'  => 'require|egt:0|regex:/^[0-9]+(.[0-9]{1,2})?$/',
            'b_amount|打款金额'  => 'require|regex:/^-?[0-9]+(.[0-9]{1,2})?$/',
            'b_currency|账户币'  => 'require|regex:/^-?[0-9]+(.[0-9]{1,2})?$/',
            'voucher_url|凭证'  => 'require',
        ]);
        
        if(!$validate->check($data)){
            // 验证失败 输出错误信息
            return $validate->getError();
        }else{
            $w[] = ['channel_id','=',$data['channel_id']];
            $r = $this->where($w)->order('id desc')->find();
            if($r){
                $data["yue_amount"] = $data['b_amount'] + $r['yue_amount'];
                $data["yue_currency"] = $data['b_currency'] + $r['yue_currency'];
            }else{
                $data["yue_amount"] = $data['b_amount'];
                $data["yue_currency"] = $data['b_currency'];
            } 
            
            $data['finance_id'] = session('uid');
            $data['type'] = 1;
            $data['create_time'] = strtotime($data['create_time']);
            try {
                $this->save($data);
                return true;
            } catch (\Throwable $th) {
                return $th->getMessage();
            }
        }
    }
    
    
}